#include "Transaction.h"
using namespace std;
// 静态变量初始化，用于生成唯一的交易编号
int Transaction::nextTransactionNumber = 1;

// 交易类构造函数，初始化交易类型、源账户ID、目标账户ID、交易金额和备注
Transaction::Transaction(
    TransactionType transType,
    const string &sourceAccId,
    const string &destAccId,
    double transAmount,
    const string &transNote) : type(transType),
                                    sourceAccountId(sourceAccId),
                                    destinationAccountId(destAccId),
                                    amount(transAmount),
                                    note(transNote)
{
    // 生成唯一的交易ID并记录当前时间戳
    transactionId = generateTransactionId();
    timestamp = time(nullptr);
}

// 获取交易ID
string Transaction::getTransactionId() const
{
    return transactionId;
}

// 获取交易类型
TransactionType Transaction::getType() const
{
    return type;
}

// 获取源账户ID
string Transaction::getSourceAccountId() const
{
    return sourceAccountId;
}

// 获取目标账户ID
string Transaction::getDestinationAccountId() const
{
    return destinationAccountId;
}

// 获取交易金额
double Transaction::getAmount() const
{
    return amount;
}

// 获取交易备注
string Transaction::getNote() const
{
    return note;
}

// 获取交易时间戳
time_t Transaction::getTimestamp() const
{
    return timestamp;
}

// 将交易类型转换为字符串表示
string Transaction::getTypeAsString() const
{
    switch (type)
    {
    case TransactionType::DEPOSIT:
        return "DEPOSIT";
    case TransactionType::WITHDRAWAL:
        return "WITHDRAWAL";
    case TransactionType::TRANSFER:
        return "TRANSFER";
    default:
        return "UNKNOWN";
    }
}

// 获取格式化的时间戳字符串
string Transaction::getFormattedTimestamp() const
{
    tm *timeInfo = localtime(&timestamp);
    ostringstream oss;
    oss << put_time(timeInfo, "%Y-%m-%d %H:%M:%S");
    return oss.str();
}

// 将交易信息转换为格式化的字符串
string Transaction::toString() const
{
    ostringstream oss;
    oss << "Transaction ID: " << transactionId << "\n"
        << "Type: " << getTypeAsString() << "\n"
        << "Source Account: " << sourceAccountId << "\n";

    // 如果是转账交易，则显示目标账户信息
    if (type == TransactionType::TRANSFER)
    {
        oss << "Destination Account: " << destinationAccountId << "\n";
    }

    // 添加金额、日期和备注信息
    oss << "Amount: ¥" << fixed << setprecision(2) << amount << "\n"
        << "Date: " << getFormattedTimestamp() << "\n";

    // 如果有备注，则显示备注信息
    if (!note.empty())
    {
        oss << "Note: " << note << "\n";
    }

    return oss.str();
}

// 生成唯一的交易ID
string Transaction::generateTransactionId()
{
    ostringstream oss;
    oss << "T" << setw(3) << setfill('0') << nextTransactionNumber++;
    return oss.str();
}